package com.hsq.reflection.testReflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ReflectCreateInstance {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class<?> cls = Class.forName("com.hsq.reflection.testReflection.User");
        Object o1 = cls.newInstance();
        System.out.println(o1);
        //有参public构造器
        Constructor<?> constructor = cls.getConstructor(String.class);
        Object o2 = constructor.newInstance("hsq");
        System.out.println(o2);
        //有参private构造器
        Constructor<?> constructor1 = cls.getDeclaredConstructor(String.class, int.class);
        //暴破（暴力破解）
        constructor1.setAccessible(true);
        Object o3 = constructor1.newInstance("Java", 99);
        System.out.println(o3);
    }
}

class User {
    private String name;
    private int age;
    public User() {

    }
    public User(String name) {
        this.name = name;
    }
    private User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "User [age=" + age + ", name=" + name + "]";
    }
}
